package cn.gwm.utils;

import cn.gwm.flink.streaming.beans.BeanSource;
import cn.gwm.flink.streaming.constant.BaseFields;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @Author: liangguang
 * @Date: 2022/6/17
 * @Description:
 */
public class HiveStringUtil<T> {

    /**
     * 默认不包含父类属性
     *
     * @param obj
     * @param <T>
     * @return
     */
    @SneakyThrows
    public static <T> String toHiveString(T obj) {
        return toHiveString(obj, false);
    }

    /**
     * 包含父类属性
     *
     * @param obj
     * @param <T>
     * @return
     */
    @SneakyThrows
    public static <T> String toHiveStringFields(T obj) {
        return toHiveString(obj, true);
    }

    /**
     * 包含父类属性
     *
     * @param obj
     * @param flag
     * @param <T>
     * @return
     */
    @SneakyThrows
    public static <T> String toHiveString(T obj, boolean flag) {
        Field[] fields = fields(obj, flag);
        StringBuilder resultString = new StringBuilder();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.get(obj) != null) {
                resultString.append(field.get(obj));
            } else {
                resultString.append("NULL");
            }
            resultString.append("\t");
        }
        return resultString.toString();
    }

    /**
     * 是否包含父类属性
     *
     * @param obj
     * @param flag
     * @param <T>
     * @return
     */
    public static <T> Field[] fields(T obj, boolean flag) {
        if (flag) {
            return obj.getClass().getFields();
        } else {
            return obj.getClass().getDeclaredFields();
        }
    }

    /**
     * json to  hive string  序列化 【落地hdfs用】
     * source 已经给定默认值
     *
     * @param source
     * @return
     */
    public static String toHiveString(JSONObject source, BeanSource.SourceEnum sourceEnum) {
        StringBuilder resultString = new StringBuilder();
        List<String> list = BeanSource.sourceList(sourceEnum);
        list.forEach(key -> {
            Object v = source.get(key);
            if (!source.containsKey(key) || StrUtil.DASHED.equals(v)) {
                resultString.append(BaseFields.defaultVal);
            } else {
                resultString.append(v);
            }
            resultString.append("\t");
        });
        return resultString.toString();
    }

}
